class StateMachine {
  constructor(initialState, transitions) {
    this.state = initialState;     // 初始状态
    this.transitions = transitions; // 状态转换规则
  }

  // 获取当前状态
  getState() {
    return this.state;
  }

  // 切换到下一个状态
  transition(action) {
    const currentState = this.state;
    const stateTransitions = this.transitions[currentState];

    // 检查当前状态是否有指定的转换规则
    if (stateTransitions && stateTransitions[action]) {
      this.state = stateTransitions[action];
      console.log(`从状态 "${currentState}" 转换到状态 "${this.state}"`);
      return this.state;
    } else {
      console.error(`不能从状态 "${currentState}" 执行动作 "${action}"`);
      return null;
    }
  }
}

// 定义状态转换规则
const transitions = {
  idle: { start: "running" },
  running: { pause: "paused", stop: "stopped" },
  paused: { resume: "running", stop: "stopped" },
  stopped: { reset: "idle" },
};

// 创建状态机实例，初始状态为 "idle"
const fsm = new StateMachine("idle", transitions);

// 测试状态转换
fsm.transition("start");   // 从 idle -> running
fsm.transition("pause");   // 从 running -> paused
fsm.transition("resume");  // 从 paused -> running
fsm.transition("stop");    // 从 running -> stopped
fsm.transition("reset");   // 从 stopped -> idle
